package com.rico.kok.controller.post;

import com.rico.kok.entity.Comment;
import com.rico.kok.entity.User;
import com.rico.kok.service.interf.CommentService;
import com.rico.kok.tool.MessageUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author：Rico_Skipper(JinYang Han)
 * @Date：2022/5/4 23:55
 */
@Controller
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private MessageUtils messageUtils;

    @RequiresRoles("user")
    @RequestMapping("/sendComment.htm")
    public String addComment(Comment comment, @RequestParam("comment") String commentContent, HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        Comment insertComment = new Comment();
        String[] split = commentContent.split("=&=>:", 2);
        String commentUserName="";
        //为-1时，表示为一层评论
        //为-2时，表示为评论错误
        Integer commentId = -1;
        if (split.length > 1) {
            String[] commentInfo = split[0].split("@", 2);
            try {
                commentId = Integer.parseInt(commentInfo[0]);
                commentUserName=commentInfo[1];
            } catch (Exception e) {
                commentId = -2;
            }
        }
        if (commentId > -1) {
            Comment selectComment = new Comment();
            selectComment.setCommentId(commentId);
            List<Comment> comments = commentService.selectComment(selectComment);
            if (comments.size() < 1) {
                messageUtils.setMsg(model, "评论不存在", "error");
                return "msg";
            }
            insertComment.setToCommentId(commentId);
            commentContent=commentUserName+":"+split[1];
        } else if (commentId == -2) {
            messageUtils.setMsg(model, "评论不正确，请勿修改评论前缀", "error");
            return "msg";
        } else {
            insertComment.setPostId(comment.getPostId());
        }
        insertComment.setUserId(user.getUserId());
        insertComment.setCommentContent(commentContent);
        commentService.insertComment(insertComment);
        return "redirect:/browsePost.htm?id=" + comment.getPostId();
    }
}
